package com.edu.controller;

import com.edu.domin.vo.ArticleVo;
import com.edu.entity.Article;
import com.edu.entity.Email;
import com.edu.properties.MyUserDetails;
import com.edu.service.IArticleService;
import com.edu.service.ICategoryService;
import com.edu.service.impl.RabbitMQProducer;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@Slf4j
@RequestMapping("/admin")
public class AdminController {
    private static final String truenotice = "你的文章审核通过，已经发布，请查收，创作者继续加油哦";
    private static final String falsenotice = "你的文章审核不通过，无法发布，请重新创作，创作者继续加油哦";
    @Autowired
    private RabbitMQProducer rabbitMQProducer;
    @Autowired
    private IArticleService  articleService;
    @Autowired
    private ICategoryService categoryService;
    /**
     * 查询所有需要批改的文章
     */
    @RequestMapping("/index")
    @PreAuthorize("hasRole('admin')")
    public String index(Model model) {
        List<ArticleVo> list = articleService.querylist();
        //返回分类集合
        model.addAttribute("categories", categoryService.list());
        model.addAttribute("articles", list);
        return "admin";
    }
    /**
     * 查询文章
     */
    @GetMapping("/article/{id}")
    public String getArticle(@PathVariable Long id, Model model)
    {
        log.info("查询文章: {}", id);
        ArticleVo vo = articleService.getVoById(id);
        model.addAttribute("article",vo);
        return "adminarticle";
    }

    /**
     * 审核文章
     */
    @GetMapping("/isApproved/{id}")
    @PreAuthorize("hasRole('admin')")
    public String approveArticle(@PathVariable Long id, @RequestParam boolean approved, Authentication authentication) {
        Email email = new Email();
        email.setSendperson(authentication.getName());
        email.setCreatedAt(LocalDateTime.now());
        //获取用户id
        Article article = articleService.query().eq("id", id).one();
        email.setUserId(article.getUserId());
        if (approved) {
            email.setEmail(truenotice);
            // 执行审核通过逻辑
            articleService.update().set("is_approved", 2).eq("id", id).update();
            rabbitMQProducer.sendEmail(email);
        } else {
            email.setEmail(falsenotice);
            // 执行审核不通过逻辑
            articleService.update().set("is_approved", 0).eq("id", id).update();
            rabbitMQProducer.sendEmail(email);
        }
        return "redirect:/admin/index";
    }



}
